package com.example.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.common.redis.service.RedisService;
import com.example.common.util.constant.OrderConstants;
import com.example.common.util.enums.PaymentEnums;
import com.example.common.util.enums.RefundStatusEnums;
import com.example.common.util.utils.DateUtils;
import com.example.common.util.utils.StringUtils;
import com.example.model.domain.entity.order.OrderInfo;
import com.example.model.domain.entity.order.PaymentInfo;
import com.example.model.domain.entity.order.RefundInfo;
import com.example.order.service.OrderInfoService;
import com.example.order.service.PaymentInfoService;
import com.example.order.service.RefundInfoService;
import com.example.order.service.WeiXinPayService;
import com.example.service.util.HttpClient;
import com.example.service.util.properties.OrderPropertiesVariable;
import com.example.service.util.service.TokenService;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author juzipi
 * @Date 2021/7/23 21:02
 * @Info
 */
@Service
public class WeiXinPayServiceImpl implements WeiXinPayService {



    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RefundInfoService refundInfoService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private OrderInfoService orderInfoService;




    @Override
    public Boolean refund(Long orderId) {
        try {
            //支付记录
            PaymentInfo paymentInfo = paymentInfoService.getPaymentInfoByOrderIdAndPaymentType(orderId, PaymentEnums.WEIXIN.getStatus());
            //添加到退款记录
            RefundInfo refundInfo = refundInfoService.insertRefundInfo(paymentInfo);
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnums.REFUND.getStatus().intValue()) {
                return true;
            }
            //调用微信接口退款，封装所需参数
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put(OrderConstants.APPID, OrderPropertiesVariable.appid);
            hashMap.put(OrderConstants.MCH_ID, OrderPropertiesVariable.partner);
            hashMap.put(OrderConstants.NONCE_STR, WXPayUtil.generateNonceStr());
            hashMap.put(OrderConstants.TRANSACTION_ID, paymentInfo.getTradeNo());
            hashMap.put(OrderConstants.OUT_TRADE_NO, paymentInfo.getOutTradeNo());
            hashMap.put(OrderConstants.OUT_REFUND_NO, OrderConstants.TK + paymentInfo.getOutTradeNo());
            hashMap.put(OrderConstants.TOTAL_FEE, OrderConstants.TOTAL_FEE_VALUE);
            hashMap.put(OrderConstants.REFUND_FEE, OrderConstants.REFUND_FEE_VALUE);

            String paramXml = WXPayUtil.generateSignedXml(hashMap, OrderPropertiesVariable.partnerKey);
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            httpClient.setXmlParam(paramXml);
            httpClient.setHttps(true);
            httpClient.setCert(true);
            httpClient.setCertPassword(OrderPropertiesVariable.partner);
            httpClient.post();
            //返回第三方数据
            String content = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            if (WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get(OrderConstants.RESULT_CODE))){
                refundInfo.setCallbackTime(DateUtils.getNowDate());
                refundInfo.setTradeNo(resultMap.get(OrderConstants.REFUND_ID));
                refundInfo.setRefundStatus(RefundStatusEnums.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                Integer integer = refundInfoService.updateRefundInfo(refundInfo);
                return integer>0;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    @Override
    public Map<String, Object> getPayQRCode(Long orderId) {
        try{
            Map<String, Object> payMap = tokenService.getPayMap(orderId);
            if (StringUtils.isNotNull(payMap)){
                return payMap;
            }
            //获取订单信息
            OrderInfo orderInfo = orderInfoService.selectOrderInfoById(orderId);
            //添加到支付记录里
            paymentInfoService.insertPaymentInfo(orderInfo,PaymentEnums.WEIXIN.getStatus());
            //设置参数调用微信生成二维码的接口
            //转换成xml形式，使用商户key加密
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put(OrderConstants.APPID,OrderPropertiesVariable.appid);
            paramMap.put(OrderConstants.MCH_ID,OrderPropertiesVariable.partner);
            paramMap.put(OrderConstants.NONCE_STR,WXPayUtil.generateNonceStr());
            String body = orderInfo.getReserveDate() + "就诊" + orderInfo.getDepname();
            paramMap.put(OrderConstants.BODY,body);
            paramMap.put(OrderConstants.OUT_TRADE_NO,orderInfo.getOutTradeNo());
            paramMap.put(OrderConstants.TOTAL_FEE,OrderConstants.TOTAL_FEE_VALUE);
            paramMap.put(OrderConstants.SPBILL_CREATE_IP,OrderConstants.SPBILL_CREATE_IP_VALUE);
            paramMap.put(OrderConstants.NOTIFY_URL,OrderConstants.NOTIFY_URL_VALUE);
            paramMap.put(OrderConstants.TRADE_TYPE,OrderConstants.TRADE_TYPE_VALUE);
            //调用微信生成二维码接口
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置参数
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap,OrderPropertiesVariable.partnerKey));
            httpClient.setHttps(true);
            httpClient.post();
            //返回第三方数据
            String content = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put(OrderConstants.ORDER_ID,orderId);
            hashMap.put(OrderConstants.TOTAL_FEE,orderInfo.getAmount());
            hashMap.put(OrderConstants.RESULTCODE,resultMap.get(OrderConstants.RESULT_CODE));
            hashMap.put(OrderConstants.CODEURL,resultMap.get(OrderConstants.CODE_URL));//二维码地址值
            if (StringUtils.isNotEmpty(resultMap.get(OrderConstants.RESULT_CODE))){
                redisService.setCacheObject(orderId.toString(),hashMap, 120L, TimeUnit.MINUTES);
            }
            return hashMap;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }



    @Override
    public Map<String, String> getPaymentTypeByOrderId(Long orderId) {

        try {
            OrderInfo orderInfo = orderInfoService.getOrderInfoById(orderId);
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put(OrderConstants.APPID,OrderPropertiesVariable.appid);
            paramMap.put(OrderConstants.MCH_ID,OrderPropertiesVariable.partner);
            paramMap.put(OrderConstants.OUT_TRADE_NO,orderInfo.getOutTradeNo());
            paramMap.put(OrderConstants.NONCE_STR,WXPayUtil.generateNonceStr());
            //设置请求内容
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap,OrderPropertiesVariable.partnerKey));
            httpClient.setHttps(true);
            httpClient.post();
            //微信接口返回的数据
            String content = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
